package com.sourcetrip.my.abs;

import com.sourcetrip.my.inter.Heap;

import java.util.Comparator;

/**
 * @author: ZhouBert
 * @date: 2020/12/25
 * @description:	抽象堆
 */
public abstract class AbstractHeap<E> implements Heap<E> {

	protected int size;
	protected Comparator<E> comparator;

	public AbstractHeap(Comparator<E> comparator) {
		this.comparator = comparator;
	}

	public AbstractHeap() {
		this(null);
	}

	@Override
	public int size() {
		return size;
	}

	@Override
	public boolean isEmpty() {
		return size == 0;
	}

	/**
	 * 1.使用 comparator
	 * 2.强制转换为 compare 进行比较；
	 * @param e1
	 * @param e2
	 * @return
	 */
	protected int compare(E e1, E e2) {
		return comparator != null ? comparator.compare(e1, e2)
				: ((Comparable<E>)e1).compareTo(e2);
	}

	//region	protected mothods
	/**
	 * 索引越界警报
	 * @param index
	 */
	protected void outOfBounds(int index) {
		throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
	}

	/**
	 * （查找的）范围检查
	 * @param index
	 */
	protected void rangeCheck(int index) {
		if (index < 0 || index >= size) {
			outOfBounds(index);
		}
	}

	/**
	 * （添加的）范围检查
	 * @param index
	 */
	protected void rangeCheckForAdd(int index) {
		if (index < 0 || index > size) {
			outOfBounds(index);
		}
	}

	//endregion
}
